package com.imarad.bio.socket.core;


import com.imarad.bio.socket.common.ClientPacket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Copyright2017-2017  AMBITION.All Rights Reserved
 *
 * Comments：
 *
 * @author huh
 *
 *         Time: 2018/2/1
 *
 *         Modified By:
 *         Modified Date:
 *         Why & What is modified:
 * @version 1.0.0
 */
class WriteSocketClient implements Runnable, SocketClient {

    private Socket mSocket;

    private boolean isRun;

    private ConnectedCallback mConnectedCallback;

    private BlockingQueue<ClientPacket> mPacketBlockingQueue = new LinkedBlockingQueue<>();

    public WriteSocketClient(Socket socket, ConnectedCallback connectedCallback) {
        mSocket = socket;
        mConnectedCallback = connectedCallback;
    }

    @Override
    public void run() {
        Thread.currentThread().setName("WriteSocketClient");
        isRun = true;
        while (isRun) {
            try {
                ClientPacket clientPacket = mPacketBlockingQueue.take();
                if (clientPacket != null) {
                    write(clientPacket);
                    mConnectedCallback.writeSuccess(clientPacket);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void stop() {
        isRun = false;
    }

    @Override
    public void send(ClientPacket clientPacket) {
        try {
            mPacketBlockingQueue.put(clientPacket);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 真实发送函数
     */
    private void write(ClientPacket clientPacket) {
        // 获取Socket的OutputStream对象用于发送数据
        OutputStream outputStream = null;
        try {
            outputStream = mSocket.getOutputStream();
            // 创建一个byte类型的buffer字节数组，用于存放读取的本地文件
            byte[] buffer = clientPacket.getSendData();
            //发送命令
            outputStream.write(buffer, 0, buffer.length);
            //发送读取的数据到服务端
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ClientPacket read() {
        throw new SocketClientException("发送数据线程不负责读取服务器信息");
    }
}
